package com.jiandaoshou.utils;

import rx.Observable;
import rx.subjects.PublishSubject;
import rx.subjects.SerializedSubject;
import rx.subjects.Subject;

@SuppressWarnings({"unused", "WeakerAccess"})
public class RxBus {
    private static volatile RxBus defaultInstance = new RxBus();
    private final Subject bus;
    private RxBus() {
      bus = new SerializedSubject<>(PublishSubject.create());
    }

    /**
     * instance
     * @return the RxBus wrapper
     */
    public static RxBus getDefault() {
        return defaultInstance;
    }

    /**
     * post an event to all subscriber
     * @param o an event
     */
    @SuppressWarnings("unchecked")
    public<T> void post (T o) {
        bus.onNext(o);
    }

    /**
     * @param eventType Type of events that this observable would like to receive
     * @return an observable
     */
    @SuppressWarnings("unchecked")
    public <T> Observable<T> toObservable(Class<T> eventType) {
        return bus.ofType(eventType);
    }
}